package com.demo.biz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.base.auth.douyin.DouCode2Session;
import com.demo.base.auth.weixin.WeCode2Session;
import com.demo.base.exception.AiException;
import com.demo.base.tokenLogin.model.UserDto;
import com.demo.base.tokenLogin.token.JwtHelper;
import com.demo.biz.user.mapper.UserMapper;
import com.demo.biz.user.model.entity.UserEntity;
import com.demo.biz.user.model.req.UserLoginReq;
import com.demo.biz.user.model.resp.UserLoginResp;
import com.demo.biz.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户表 服务实现类
 *
 * @author 曳戈泰尔
 * @since 2023-03-14
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    /** 注入微信auth */
    private WeCode2Session weCode2Session;

    @Autowired
    public void setWeCode2Session(WeCode2Session weCode2Session) {
        this.weCode2Session = weCode2Session;
    }

    /** 注入抖音auth */
    private DouCode2Session douCode2Session;

    @Autowired
    public void setDouCode2Session(DouCode2Session douCode2Session) {
        this.douCode2Session = douCode2Session;
    }

    /** 注入用户Mapper */
    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 用户登录
     *
     * @param userLoginReq
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginResp userLogin(UserLoginReq userLoginReq) {

        // 小程序openId
        String openId;

        /** Switch选择第三方登录 */
        Integer type = userLoginReq.getType();
        switch (type) {
                // 微信小程序登录
            case 0:
                openId = weCode2Session.getOpenIdByCode(userLoginReq.getCode());
                break;

                // 抖音小程序登录
            case 1:
                openId = douCode2Session.getOpenIdByCode(userLoginReq.getCode());
                break;

                // 错误类型登录
            default:
                throw new AiException("登录失败，请重试");
        }

        /* 判断openId是否为空，为空则登录失败 */
        if (StringUtils.isBlank(openId)) {
            throw new AiException("登录失败，请重试");
        }

        // 根据openId创建用户token
        String token = this.createUserToken(type, openId);

        // 判断token是否为空，为空则登录失败
        if (StringUtils.isBlank(token)) {
            throw new AiException("登录失败，请重试");
        }

        // 构造返回体
        return UserLoginResp.builder().token(token).code(userLoginReq.getCode()).build();
    }

    /**
     * 返回用户token
     *
     * @param type 小程序类型
     * @param openId 小程序openId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createUserToken(Integer type, String openId) {

        // 查询用户是否存在，不存在需要新增用户记录
        LambdaQueryWrapper<UserEntity> lqwUser = new LambdaQueryWrapper<>();
        lqwUser.select(UserEntity::getId);
        lqwUser.eq(UserEntity::getOpenId, openId);
        lqwUser.eq(UserEntity::getType, type);
        UserEntity user = userMapper.selectOne(lqwUser);

        // 定义token用户信息
        UserDto userDto;

        // 创建用户
        if (user == null) {
            UserEntity insertUser =
                    UserEntity.builder()
                            .createTime(LocalDateTime.now())
                            .updateTime(LocalDateTime.now())
                            .openId(openId)
                            .type(type)
                            .build();
            if (userMapper.insert(insertUser) != 1) {
                log.error("新增用户插入数据库失败，用户openId：{}", openId);

                throw new AiException("登录失败，请重试");
            }

            userDto = UserDto.builder().userId(insertUser.getId()).build();
        } else {
            // 根据用户ID创建用户token
            userDto = UserDto.builder().userId(user.getId()).build();
        }

        return JwtHelper.generateToken(userDto);
    }
}
